package com.clusterswisdom.horn.api.tmall.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.clusterswisdom.horn.api.ioc.api.HornConfig;
import com.taobao.api.FileItem;

public class TmallUtil {

	public static final String KEY_PUSHSERVER = "imgServer";
	
	public static FileItem getFileItem(String url) throws IOException {
		return new FileItem(getFileName(url), getDefaultTkImge(url));
	}
	
	public static double getPrice(String price) {
		if (price == null) {
			return 0.0d;
		}
		
		try {
			return Double.parseDouble(price);
			
		} catch (Exception e) {
			return 0.0d;
			
		}
	}
	
	private static String getFileName(String url) {
		int index = url.lastIndexOf("/");
		return url.substring(index + 1);
	}
	
	private static byte[] getDefaultTkImge(String url) throws IOException {
		url = HornConfig.getConfig().getProperty(KEY_PUSHSERVER) +  url;
		
	    URLConnection conn = new URL(url).openConnection();
	    InputStream is = conn.getInputStream(); 
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] readerBuffer = new byte[1024];
		int len = -1;
		
		while ((len = is.read(readerBuffer)) != -1) {
			output.write(readerBuffer, 0, len);
		}
		
		return output.toByteArray();
	}
}
